<?php

class TradeAccount extends DataObject {
    private static $singular_name = "Trade Account";
    private static $plural_name = "Trade Accounts";
	
	private static $db = array(
        'TradeUnit' => 'Int',
        'TradeDeposit' => 'TradeCurrency'
    );
	
	private static $has_one = array(
		'Member' => 'Member',
		'TradeSetting' => 'TradeSetting'
	);
	
	private static $searchable_fields = array(
    	'Member.Username',
    	'Member.FirstName',
    	'Member.Surname',
    	'TradeUnit' => array(
            'filter' => 'GreaterThanOrEqualFilter'
        ),
		'TradeDeposit' => array(
            'filter' => 'GreaterThanOrEqualFilter'
        ),
        'TradeSettingID'
    );

    private static $summary_fields = array(
    	'Member.Username',
    	'Member.Name',
    	'TradeUnit',
    	'CurrentUnit',
        'TradeDeposit',
        'TradeSetting.Title'
    );
	
	private static $casting = array(
		'CurrentUnit' => 'Int',
		'CurrentValue' => 'TradeCurrency',
		'AvailableUnit' => 'Int',
		'AvailableValue' => 'TradeCurrency'
	);
	
	public function fieldLabels($includerelations = true) {
        $labels = parent::fieldLabels($includerelations);

		$labels['TradeUnit'] = _t('TradeAccount.TRADE_UNIT', 'Trade Unit');
		$labels['CurrentUnit'] = _t('TradeAccount.CURRENT_UNIT', 'Current Unit');
		$labels['TradeDeposit'] = _t('TradeAccount.TRADE_DEPOSIT', 'Trade Deposit');
		$labels['Member.Username'] = _t('TradeAccount.USERNAME', 'Username');
		$labels['Member.FirstName'] = _t('TradeAccount.FIRST_NAME', 'First Name');
		$labels['Member.Surname'] = _t('TradeAccount.SURNAME', 'Surname');
		$labels['Member.Name'] = _t('TradeAccount.NAME', 'Name');
		$labels['TradeSetting'] = _t('TradeAccount.TRADE_SETTING', 'Trade Setting');
		$labels['TradeSettingID'] = _t('TradeAccount.TRADE_SETTING', 'Trade Setting');
		$labels['TradeSetting.Title'] = _t('TradeAccount.TRADE_SETTING', 'Trade Setting');

        return $labels;
    }
	
	function getCurrentUnit(){
		return $this->TradeUnit - TradeOrder::get()->filter('MemberID', $this->MemberID)->filter('TradeSettingID', $this->TradeSettingID)->filter('Status', 'Pending')->filter('Type', 'Sell')->filter('Remaining:GreaterThan', 0)->sum('Remaining');
	}
	
	function getCurrentValue(){
		return $this->getCurrentUnit() * $this->TradeSetting()->Price;
	}
	
	function getAvailableUnit(){
		return intval(($this->getCurrentValue() - $this->TradeDeposit) / ($this->TradeSetting()->Price * (1 + $this->TradeSetting()->SellFeePercentage)));
	}
	
	function getAvailableValue(){
		return $this->getCurrentValue() - $this->TradeDeposit;
	}

    function canView($member = false) {
        return true;
    }

    function canEdit($member = false) {
        return false;
    }

    function canDelete($member = false) {
        return false;
    }

    function canCreate($member = false) {
        return false;
    }
}
?>